package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.border.TitledBorder;

import model.Filter;

import resources.ResourceProvider;

/**
 * class to display for Filter panel
 *
 */
public class FilterPanel extends JPanel
{
    private static final long serialVersionUID = -2529290051485146726L;
    
    private JLabel filterName;
    
    private JTextField filterNameTextField;

    private JLabel textLabel;
    
    private JTextField keywordToSearchTextField;
    
    private JLabel selectFolderLabel;
    
    private JTextField selectMoveFolderText;
    
    private JButton selectMoveFolderButton;
    
    private MailDisplayArea mailDisplayArea;
    
    private String moveToFolderPath;
    
    private JComboBox<String> combox;
    
    private JLabel receivedFromLabel;
    
    private JLabel toSearchInLabel;
    
    private JTextField receivedFromText;
    
    private JCheckBox subjectCheckBox;
    
    private JCheckBox messageCheckBox;
        
    private String enabled = "Enabled";
    private String disabled = "Disabled";
    
    /**
     * Filter panel
     * @param mailDisplayArea 
     */
    public FilterPanel(MailDisplayArea mailDisplayArea)
    {
        this.moveToFolderPath = "";
        this.initialize();
        this.mailDisplayArea = mailDisplayArea;
    }
    
    /**
     * initialization
     */
    private void initialize()
    {
        
        TitledBorder title = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black), "Create Filter");
        this.setBorder(title);
        this.setLayout(null);
        
        filterName = new JLabel("Name of Filter :");
        filterName.setBounds(new Rectangle(32,44,125,30));
        filterName.setFont(new Font("Times New Roman",Font.PLAIN,18));
        this.add(filterName);
        
        filterNameTextField = new JTextField();
        filterNameTextField.setBounds(new Rectangle(155,44,400,30));
        this.add(filterNameTextField);
        
        
        receivedFromLabel = new JLabel("Received From :");
        receivedFromLabel.setBounds(new Rectangle(32,104,125,30));
        receivedFromLabel.setFont(new Font("Times New Roman",Font.PLAIN,18));
        this.add(receivedFromLabel);
        
        
        receivedFromText = new JTextField();
        receivedFromText.setBounds(new Rectangle(155,104,400,30));
        this.add(receivedFromText);
        
        textLabel = new JLabel("Text to Search  :");
        textLabel.setBounds(new Rectangle(32,154,125,30));
        textLabel.setFont(new Font("Times New Roman",Font.PLAIN,18));
        this.add(textLabel);
        
        keywordToSearchTextField = new JTextField();
        keywordToSearchTextField.setBounds(new Rectangle(155,154,400,30));
        this.add(keywordToSearchTextField);
                
        toSearchInLabel = new JLabel("Search Inside    :");
        toSearchInLabel.setBounds(new Rectangle(32,204,125,30));
        toSearchInLabel.setFont(new Font("Times New Roman",Font.PLAIN,18));
        this.add(toSearchInLabel);
        
        
        subjectCheckBox = new JCheckBox("Subject");
        subjectCheckBox.setBounds(new Rectangle(155,204,100,30));
        this.add(subjectCheckBox);
        
        messageCheckBox = new JCheckBox("Message");
        messageCheckBox.setBounds(new Rectangle(275,204,100,30));
        this.add(messageCheckBox);
        
        selectFolderLabel = new JLabel("Folder to Move :");
        selectFolderLabel.setBounds(new Rectangle(32,254,125,30));
        selectFolderLabel.setFont(new Font("Times New Roman",Font.PLAIN,18));
        this.add(selectFolderLabel);
        
        selectMoveFolderButton = new JButton("Select Folder");
        selectMoveFolderButton.setBounds(new Rectangle(152,254,130,30));
        selectMoveFolderButton.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e)
            {
                EmailFolderNode optionInbox = new EmailFolderNode(ResourceProvider.INBOX);
                String user = FilterPanel.this.mailDisplayArea.getEmailApplicationView().getController().getUser();
                optionInbox.setPersistenceFilePath(ResourceProvider.getRootFolderPath(ResourceProvider.INBOX, user));
                JTree tree = new JTree(optionInbox); 
                FilterPanel.this.mailDisplayArea.loadPersistenceFolders(optionInbox);
                JPanel panel = new JPanel();
                panel.setLayout(new BorderLayout(10, 10));
                TitledBorder title = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black), "");
                panel.setBorder(title);
                panel.add(new JScrollPane(tree));
                for (int j = 0; j < tree.getRowCount(); j++) 
                {
                    tree.expandRow(j);
                }
                           
                int optionSelected = JOptionPane.showConfirmDialog(null,
                     panel,
                     "Move To",
                     JOptionPane.OK_CANCEL_OPTION,
                     JOptionPane.PLAIN_MESSAGE);
                
                if(optionSelected == JOptionPane.OK_OPTION)
                {
                    EmailFolderNode selectedNode = (EmailFolderNode) tree.getLastSelectedPathComponent();
                    String destinationPathToMove = selectedNode.getPersistenceFilePath();
                    
                    String userid = FilterPanel.this.mailDisplayArea.getEmailApplicationView().getController().getUser();
                    String mailBoxPath = ResourceProvider.getRootFolderPath(ResourceProvider.MAILBOX, userid) + ResourceProvider.getFilePathSeperator();
                    moveToFolderPath = destinationPathToMove;
                    selectMoveFolderText.setText(destinationPathToMove.replace(mailBoxPath, ""));
                } 
            }
        });
        this.add(selectMoveFolderButton);
        
        selectMoveFolderText = new JTextField();
        selectMoveFolderText.setEditable(false);
        selectMoveFolderText.setText("<<Select Folder to Move Email which meets filter criteria>>");
        selectMoveFolderText.setBounds(new Rectangle(152,284,400,30));
        this.add(selectMoveFolderText);
        
        JLabel filterStatusLabel = new JLabel("Filter Status      :");
        filterStatusLabel.setBounds(new Rectangle(32,314,125,30));
        filterStatusLabel.setFont(new Font("Times New Roman",Font.PLAIN,18));
        this.add(filterStatusLabel);
        
        String[] names = new String[]{disabled,enabled};
        combox = new JComboBox<String>(names);
        combox.setBounds(new Rectangle(155,314,130,30));
        this.add(combox);
        
    }

    /**
     * get Filter object
     * @return the filter
     */
    public Filter getFilter()
    {
        Filter filter = new Filter(filterNameTextField.getText().trim(), keywordToSearchTextField.getText().trim(), moveToFolderPath,receivedFromText.getText().trim());
        String selection = (String)combox.getSelectedItem();
        if(selection.endsWith(enabled))
        {
            filter.setActivation(true);
            
            //set next priority
            String user = this.mailDisplayArea.getEmailApplicationView().getController().getUser();
            String filterPath = ResourceProvider.getRootFolderPath(ResourceProvider.FILTERS, user);

            List<Filter> filterList = this.mailDisplayArea.getEmailApplicationView().getController().requestFiltersFromPersistence(filterPath);        
            
            List<Filter> activeFilters = new LinkedList<Filter>();
            int nextPriority = 0;
            for(Filter filR : filterList)
            {
                if(filR.isEnabled())
                {
                    activeFilters.add(filR);
                    if(filR.getPriority() > nextPriority)
                    {
                        nextPriority = filR.getPriority();
                    }
                }   
            }
            filter.setPriority(nextPriority + 1);
            
        }
        else        
        {
            filter.setActivation(false);
            filter.setPriority(0);
        }
        
        if(subjectCheckBox.isSelected())
        {
            filter.setSearchInSubject(true);
        }
        
        if(messageCheckBox.isSelected())
        {
            filter.setSearchInMessage(true);
        }
        
        return filter;
    }

    /**
     * load Filter to this panel
     * @param filR the given filter
     */
    public void loadFilter(Filter filR)
    { 
        filterNameTextField.setText(filR.getFilterName());
        filterNameTextField.setEditable(true);
        
        keywordToSearchTextField.setText(filR.getKeywordToSearch());
        keywordToSearchTextField.setEditable(true);
        
        receivedFromText.setText(filR.getReceiver());
        receivedFromText.setEditable(true);
        
        selectMoveFolderText.setText(filR.getDestination());
        selectMoveFolderText.setEditable(true);
        
        moveToFolderPath = filR.getDestination();
        
        
        String userid = FilterPanel.this.mailDisplayArea.getEmailApplicationView().getController().getUser();
        String mailBoxPath = ResourceProvider.getRootFolderPath(ResourceProvider.MAILBOX, userid) + ResourceProvider.getFilePathSeperator();
        selectMoveFolderText.setText(moveToFolderPath.replace(mailBoxPath, ""));
        
        boolean isActive = filR.isEnabled();
        if(isActive)
        {
            combox.setSelectedItem(enabled);
        }
        else
        {
            combox.setSelectedItem(disabled);
        }

        subjectCheckBox.setSelected(filR.isSearchInSubject());
        messageCheckBox.setSelected(filR.isSearchInMessage());
       
    }
    
}
